﻿using SelfMadeMillionaire.Core;
using SelfMadeMillionaire.Core.Entities;
using SelfMadeMillionaire.Core.Enums;
using SelfMadeMillionaire.Core.Services;
using SelfMadeMillionaire.Web.Infrastructure.Controllers;
using SelfMadeMillionaire.Web.Infrastructure.Formatters;
using SelfMadeMillionaire.Web.Infrastructure.ViewModels.Newsletters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using PagedList;
using SelfMadeMillionaire.Core.Specifications.Publications;
using System.IO;
using System.Configuration;

namespace SelfMadeMillionaire.Web.Infrastructure.Controllers
{
	public class NewslettersController : BaseController
	{
		INewsletterService _newsletterService;
        ISubscriberService _subscriberService;
        INewsletterReadService _newsletterReadService;

        public NewslettersController(INewsletterService newsletterService, ISubscriberService subscriberService, INewsletterReadService newsletterReadService)
		{
			_newsletterService = newsletterService;
            _subscriberService = subscriberService;
            _newsletterReadService = newsletterReadService;
		}

		public ActionResult TrackingPortfolioPerfomanceIssues()
		{
			var issueTypes = _newsletterService.GetIssueTypes();
			return RedirectToAction("Index", new { startDate = new DateTime(DateTime.Now.Year, 1, 1), endDate = new DateTime(DateTime.Now.Year, 12, 31), issueType = issueTypes.Single(x=>x.Title == "Portfolio Performance").ID });
		}

        private SubscriptionType GetMinAccessLevel()
        {
            var minAccessLevel = SubscriptionType.Free;
            if (Request.IsAuthenticated)
                minAccessLevel = _subscriberService.GetMinAccessLevel(User.Identity.Name);

            return minAccessLevel;
        }

        public ActionResult Index(DateTime? startDate, DateTime? endDate, ProductType? selectedProduct, byte? selectedIssueType, string symbols, string title, int? page, string sort)
		{
            ClearProductTypeInSession();

			int pageIndex = page ?? 1;
			int pageSize = 10;
			var issueTypes = _newsletterService.GetIssueTypes();

			var productType = GetProductTypeDepenenOnReferrer(selectedProduct);

			startDate = startDate ?? DateTime.Today.AddMonths(-1);
			endDate = endDate ?? DateTime.Today;

            IEnumerable<Newsletter> list = _newsletterService.GetList(startDate, endDate, selectedProduct, selectedIssueType, symbols, title, (byte)GetMinAccessLevel(), null, false);
            if (!string.IsNullOrEmpty(sort))
            {
                string[] sortArr = sort.Split(',');
                if (sortArr[1] == "0")
                {

                    switch (sortArr[0])
                    {
                        case "0":
                            list = list.OrderBy(i => i.Date);
                            break;
                        case "1":
                            list = list.OrderBy(i => i.IssueType.Title);
                            break;
                        case "2":
                            list = list.OrderBy(i => i.Symbols);
                            break;
                        case "3":
                            list = list.OrderBy(i => ProductTypeFormatter.GetProductTypeName((ProductType)Enum.Parse(typeof(ProductType), i.Letter.ToString())));
                            break;
                        case "4":
                            list = list.OrderBy(i => i.Title);
                            break;
                    }

                }
                else
                {
                    switch (sortArr[0])
                    {
                        case "0":
                            list = list.OrderByDescending(i => i.Date);
                            break;
                        case "1":
                            list = list.OrderByDescending(i => i.IssueType.Title);
                            break;
                        case "2":
                            list = list.OrderByDescending(i => i.Symbols);
                            break;
                        case "3":
                            list = list.OrderByDescending(i => ProductTypeFormatter.GetProductTypeName((ProductType)Enum.Parse(typeof(ProductType), i.Letter.ToString())));
                            break;
                        case "4":
                            list = list.OrderByDescending(i => i.Title);
                            break;
                    }
                }
            }
            
			var model = new NewsletterListViewModel
			{
				Newsletters = list.ToPagedList(pageIndex, pageSize),
				StartDate = startDate,
				EndDate = endDate,
				ProductTypes = GetProductTypes(productType),
				SelectedProduct = productType.HasValue ? productType.Value : ProductType.None,
				IssueTypes = GetIssueTypes(issueTypes, selectedIssueType.HasValue ? selectedIssueType.ToString() : null),
				SelectedIssueType = selectedIssueType,
				Symbols = symbols,
				Title = title,
                SortOrder = sort
			};

			if (Request.IsAjaxRequest())
				return PartialView("NewslettersList", model);

			return View(model);
		}

		[HttpGet]
		public ActionResult Details(int id)
		{
            NewsletterPublicEditViewModel model = new NewsletterPublicEditViewModel();
            model.Item = _newsletterService.Get(id);

            if ((model.Item.MinAccessLevel > (byte)GetMinAccessLevel()) && (model.Item.Letter != (byte)ProductType.MaggiesMoneyMountain))
            {
                return RedirectToAction("Index");
            }

            if (model.Item.IsHide)
            {
                return RedirectToAction("Index");
            }

            Session[Constants.PRODUCT_TYPE_SESSION_KEY] = model.Item.Letter;


            if (GetProductType() == ProductType.MaggiesMoneyMountain)
            {
                model.OtherIssue = _newsletterService.GetList(new RecentIssuesSpecification(4, ProductType.MaggiesMoneyMountain, SubscriptionType.Platinum, model.Item.IssueType.ID, model.Item.ID, ""));
            }
            else
            {
                var m = _newsletterService.GetList(new RecentIssuesSpecification(4, GetProductType().HasValue ? GetProductType().Value : ProductType.SelfMadeMillionaire, GetMinAccessLevel(), model.Item.IssueType.ID, model.Item.ID, "")).ToList().OrderByDescending(i => i.Date);
                model.OtherIssue = m;
            }
            
            Subscriber subs = _subscriberService.Get(User.Identity.Name);
            if (subs != null)
                _newsletterReadService.MarkRead(model.Item.ID, subs.ID);

            return View(model);
		}

        [HttpGet]
        public ActionResult BySymbol(int id, string symbol)
        {
            NewslettersBySymbolViewModel model = new NewslettersBySymbolViewModel();
            model.Symbol = symbol;
            model.NewsletterId = id;
            
            Newsletter item = _newsletterService.Get(id);
            model.NewsletterSymbols = item.Symbols;
            
            string[] arrSymbols = item.Symbols.Split(new string[] { ", " }, StringSplitOptions.None);
            if (string.IsNullOrEmpty(model.Symbol))
                model.Symbol = arrSymbols[0];

            if (GetProductType() == ProductType.MaggiesMoneyMountain)
            {
                model.BySymbolIssue = _newsletterService.GetList(new RecentIssuesSpecification(4, ProductType.MaggiesMoneyMountain, SubscriptionType.Platinum, item.IssueType.ID, item.ID, model.Symbol));
            }
            else
            {
                var m = _newsletterService.GetList(new RecentIssuesSpecification(4, GetProductType().HasValue ? GetProductType().Value : ProductType.SelfMadeMillionaire, GetMinAccessLevel(), item.IssueType.ID, item.ID, model.Symbol)).ToList();
                foreach (var i in _newsletterService.GetMmmRecentIssues())
                {
                    m.Insert(0, i);
                }

                model.BySymbolIssue = m;
            }
            return View(model);
        }

        public FilePathResult NewsletterFile(int ID)
        {
            var item = _newsletterService.Get(ID);

            if ((item.MinAccessLevel > (byte)GetMinAccessLevel()) && (item.Letter != (byte)ProductType.MaggiesMoneyMountain))
            {
                return null;
            }
            if (item.IsHide)
            {
                return null;
            }

            string path = Path.Combine(ConfigurationManager.AppSettings["PdfFilesStorePath"], item.PdfFileName);
            return File(path, "application/pdf"); 
        }


	}
}
